package com.hello.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hello.sky.context.BaseContext;
import com.hello.sky.mapper.AddressBookMapper;
import com.hello.sky.model.entity.AddressBook;
import com.hello.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 地址簿 服务实现类
 * </p>
 *
 * @author D
 */
@Slf4j
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Override
    public List<AddressBook> getAllAddrByCurrentUser() {
        return baseMapper.getListByUserId(BaseContext.getCurrentId());
    }

    @Override
    public void addAddr(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        baseMapper.insert(addressBook);
    }

    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        baseMapper.updateIsDefaultByUserId(addressBook);

        //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        baseMapper.updateAddr(addressBook);
    }

    @Override
    public AddressBook getDefaultAddr() {
        LambdaQueryWrapper<AddressBook> qr = new LambdaQueryWrapper<AddressBook>().eq(AddressBook::getId, BaseContext.getCurrentId()).eq(AddressBook::getIsDefault, 1);
        List<AddressBook> list = list(qr);

        if (list != null && list.size() > 0){
            return list.get((0));
        }else {
            return null;
        }
    }

    public void update(AddressBook addressBook) {
        baseMapper.updateAddr(addressBook);
    }
}
